package com.allenkerr.util;

/**
 * Created by 小柯 on 17/7/7.
 */
public class MathUtils {

    /**
     * 二进制字符串 转 十六进制字符串
     *
     * @param binary
     * @return String
     */
    public static String binaryStringToHexString(String binary) {
        //抛出 IllegalArgumentException(非法参数异常)
        if (binary.length() % 4 != 0)
            throw new IllegalArgumentException("参数不合法！");

        //二进制 转 十进制
        Integer integer = Integer.valueOf(binary, 2);
        //十进制 转 十六进制
        String hex = Integer.toHexString(integer);
        //十六进制字符串长度处理
        int capacity = binary.length() >> 2;
        if (hex.length() < capacity) {
            StringBuilder builder = new StringBuilder(capacity);
            for (int i = 0; i < capacity - hex.length(); i++) {
                builder.append("0");
            }
            hex = builder.append(hex).toString();
        }
        return hex;
    }

    /**
     * 二进制字符串(StringBuilder类型) 转 十六进制字符串
     *
     * @param binary
     * @return String
     */
    public static String binaryStringBuilderToHexString(StringBuilder binary) {
        //调用 binaryStringToHexString
        return binaryStringToHexString(binary.toString());
    }

    /**
     * byte[]数组 转 十六进制字符串
     *
     * @param bytes
     * @return String
     */
    public static String bytesToHexString(byte[] bytes) {
        ////抛出 IllegalArgumentException(非法参数异常)
        if (bytes.length % 4 != 0)
            throw new IllegalArgumentException("参数不合法！");
        //bytes 转 StringBuilder
        StringBuilder binary = new StringBuilder(bytes.length);
        for (byte aByte : bytes) {
            binary.append(aByte);
        }
        //调用 binaryStringBuilderToHexString
        return binaryStringBuilderToHexString(binary);
    }

}
